package com;

import com.alibaba.fastjson.JSON;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * 添加博客记录
 */
@WebServlet("/addBlog")
public class BlogServletAdd extends HttpServlet {
    DbUtil dbUtil = new DbUtil();

    public void init() throws ServletException
    {
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            Map res = new HashMap();
            String content = req.getParameter("content");
            if(null != content && !content.equals("")){
                dbUtil.addBlog(content);
                res.put("status",HttpServletResponse.SC_OK);//200
                res.put("msg","添加微博记录成功");
            }else{
                res.put("status",303);//保存失败
                res.put("msg","添加微博记录失败");
            }
            //响应的是json
            resp.setContentType("application/json;charset=utf-8");
            //获得对象的json格式数据
            String jsonRes =  JSON.toJSONString(res);;//gson,jaskon
            resp.getOutputStream().write(jsonRes.getBytes(StandardCharsets.UTF_8));
            resp.flushBuffer();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void destroy()
    {
        // 什么也不做
    }
}
